<template>
  <div>
    <header class="game_modal_header ">酒店推荐</header>
    <div class="main_box">
      <div class="search_box">
        <el-row :gutter="20">
          <el-col :span="6.5">
            <span>按星级选择</span>
            <el-select v-model="HotelListQO.HotelRatingCode" size="mini" placeholder="星级" filterable @change="getData()">
              <el-option label="全部" value="" />
              <el-option v-for="item in dict.hotelRating" :key="item.code" :label="item.value" :value="item.code" />
            </el-select>
          </el-col>
          <el-col :span="6.5">
            <span>酒店名称</span>
            <el-input v-model="HotelListQO.Filter" placeholder="请输入" size="mini" clearable @change="getData()" />
          </el-col>
          <el-col :span="8">
            <el-button type="primary" size="mini" @click="getData()">查询</el-button>
            <el-button type="warning" size="mini" @click="reset()">重置</el-button>
          </el-col>
        </el-row>
      </div>
      <div v-loading="loading" class="gl_mb_20 gl_pb_20 list" style="max-height: 800px;">
        <div
          v-if="hotelData.length > 0"
          ref="scrollH"
          v-infinite-scroll="load"
          :infinite-scroll-immediate="false"
          :infinite-scroll-disabled="disabled"
          style="overflow:auto; overflow-y: scroll;"
        >
          <div ref="contentBox">
            <div v-for="item in hotelData" :key="item.id">
              <div class="content_box" :class="[ item.isShowDetail ? 'content_border_b': '' ]">
                <el-row :gutter="20" type="flex" justify="space-between">
                  <el-col :span="11">
                    <div v-if="item.hotel.imagePath" class="gl_dis_ib gl_middle">
                      <img class="hotelPhoto" :src="getStaticFileUrl(item.hotel.imagePath)" alt="" @error="errorPhoto">
                    </div>
                    <div class="gl_dis_ib gl_top">
                      <p class="title gl_mb_5 gl_ellipsis">{{ item.hotel.name }}</p>
                      <p class="address gl_mb_5 gl_ellipsis">{{ item.hotel.address }}</p>
                      <p class="gl_fs_14">
                        <el-popover
                          placement="bottom-start"
                          width="400"
                          trigger="click"
                        >
                          <div>
                            <p class="title gl_mb_10">{{ item.hotel.name }}</p>
                            <div class="gl_dis_ib gl_middle">
                              <img v-if="item.hotel.imagePath" class="hotelPhoto" :src="getStaticFileUrl(item.hotel.imagePath)" alt="" @error="errorPhoto">
                            </div>
                            <p class="gl_mt_15">酒店介绍</p>
                            <p>{{ item.hotel.description || '- -' }}</p>
                          </div>
                          <el-button slot="reference" type="text" style="height: 28px; color: #000">
                            <span class="gl_mr_5">查看详情</span>
                            <i class="el-icon-caret-bottom" />
                          </el-button>
                        </el-popover>
                      </p>
                    </div>
                  </el-col>
                  <el-col :span="7">
                    <div class="gl_mt_20 time">
                      <p>入住时间：{{ item.hotel.checkInTime || '- -' }}</p>
                      <p>离店时间：{{ item.hotel.checkOutTime || '- -' }}</p>
                    </div>
                  </el-col>
                  <el-col :span="6" align="right">
                    <div class="gl_mr_10 gl_mt_10">
                      <el-rate v-model="hotelRatingCode[item.hotel.hotelRatingCode]" disabled />
                      <el-button type="text" size="small" style="font-size: 14px; margin-top: 30px" @click="showDetail(item)">
                        <span class="gl_pr_10">展开</span>
                        <span class="gl_pr_10"><i class="el-icon-arrow-right" :class="[ item.isShowDetail ? 'arrow_down': 'arrow_right' ]" /></span>
                      </el-button>
                    </div>
                  </el-col>
                </el-row>
              </div>
              <div v-show="item.isShowDetail" class="gl_ml_20">
                <div v-if="item.hotel.rooms.length > 0" v-loading="item.roomLoading">
                  <div v-for="(jtem, jndex) in item.hotel.rooms" :key="jtem.id" class="gl_py_15 gl_ml_20 gl_px_20" :class="[ jndex !== item.hotel.rooms.length -1 ? 'content_border_b': '' ]">
                    <el-row :gutter="20" type="flex" justify="space-between">
                      <el-col :span="10">
                        <div class="gl_dis_ib gl_middle">
                          <img v-if="jtem.room.imagePath" class="roomPhoto" :src="getStaticFileUrl(jtem.room.imagePath)" alt="" @error="errorPhoto">
                        </div>
                        <div class="gl_dis_ib gl_top">
                          <p class="title gl_fs_14">{{ jtem.room.name || '- -' }}</p>
                          <p class="address gl_mb_5">
                            <span class="gl_mr_5">{{ jtem.room.area || '- -' }}㎡</span>
                            <span class="gl_mr_10">
                              <span v-if="jtem.room.hasWindow == null">- -</span>
                              <span v-else>{{ jtem.room.hasWindow ? '有窗' : '无窗' }}</span>
                            </span>
                          </p>
                          <p class="addBed gl_fs_14">
                            <span v-if="jtem.hasExtraBed">加床：￥{{ (jtem.extraBedPrice / 100).toFixed(2) }}/床/每晚</span>
                          </p>
                        </div>
                      </el-col>
                      <el-col :span="3">
                        <p class="pt_30">{{ jtem.room.bedType.name || '- -' }}</p>
                      </el-col>
                      <el-col :span="3">
                        <p class="pt_30">{{ jtem.room.breakfastType.name || '- -' }}</p>
                      </el-col>
                      <el-col :span="3">
                        <p class="pt_30">{{ jtem.room.personCount ? jtem.room.personCount + '人' : '- -' }}</p>
                      </el-col>
                      <el-col :span="3">
                        <p class="pt_30">剩 {{ jtem.count }} 间</p>
                      </el-col>
                      <el-col :span="3">
                        <p class="price">￥{{ (jtem.price / 100).toFixed(2) || '- -' }}</p>
                      </el-col>
                      <el-col :span="4" class="gl_pt_10">
                        <div class="gl_pt_20 gl_ml_5">
                          <el-button type="info" :disabled="!canOrder || jtem.count == 0" :class="[ canOrder && jtem.count != 0 ? 'order': 'no_order' ]" size="small" @click="order(jtem, 'order')">立即预定</el-button>
                        </div>
                      </el-col>
                    </el-row>
                  </div>
                </div>
                <div v-else class="gl_noData_mockTable">
                  <p>暂无房型数据</p>
                </div>
              </div>
            </div>
            <el-row
              v-if="dataLoading"
              v-loading="dataLoading"
              style="height: 50px"
              element-loading-text="拼命加载中"
              element-loading-spinner="el-icon-loading"
            />
          </div>
        </div>
        <div v-else style="line-height: 400px" class="gl_noData_mockTable">
          <p>暂无数据</p>
        </div>
      </div>
    </div>
    <div v-if="orderData.hotelEntrys && orderData.hotelEntrys.length > 0" class="main_box order_table">
      <p class="title gl_ml_20 gl_pl_5">已订购的酒店</p>
      <el-table v-loading="tableLoading" class="gl_mt_10 gl_table_noBorder" :data="orderData.hotelEntrys" size="mini">
        <el-table-column prop="hotelName" label="酒店名称" />
        <el-table-column prop="roomName" label="房间名称" />
        <el-table-column prop="reserveNumber" label="预定数量" :width="80" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.reserveNumber }}间</span>
          </template>
        </el-table-column>
        <el-table-column label="入住/退房时间" :width="160">
          <template slot-scope="{ row }">
            <p>{{ row.checkInDate | FormatDate('yyyy-MM-dd') }} -- {{ row.checkOutDate | FormatDate('yyyy-MM-dd') }}</p>
            <p>共{{ row.dayNum }}晚</p>
          </template>
        </el-table-column>
        <el-table-column prop="extraBedNumber" label="加床数量" :width="70" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.extraBedNumber || '- -' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="receptionName" label="预定人姓名" />
        <el-table-column prop="receptionPhoneNumber" label="预订人手机号" :width="100" />
        <el-table-column prop="remark" label="备注" :width="100">
          <template slot-scope="{ row }">
            <p>{{ row.remark || '- -' }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额">
          <template slot-scope="{ row }">
            <span>￥{{ (row.amount / 100).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" :width="90" fixed="right">
          <template slot-scope="{ row }">
            <el-button type="text" size="mini" @click="edit(row, 'edit')">编辑</el-button>
            <el-button type="text" size="mini" @click="remove(row)">
              <span class="gl_color_error">删除</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-row class="gl_mt_20 gl_pt_5" type="flex" justify="center">
      <el-col align="center">
        <el-button v-if="hasNext" type="primary" size="small" style="border-radius: 8px;" @click="toNext()">下一步</el-button>
        <el-button v-if="toOrder" type="primary" size="small" style="border-radius: 8px; background: #ff704a; border-color: #ff704a;" @click="toNext()">去结算</el-button>
      </el-col>
    </el-row>
    <HotelOrder ref="hotelOrder" />
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import defaultHotelImg from '@/assets/images/face_default.png';
import HotelOrder from './hotelOrder.vue';
import {
  api_GET_EventsManagementLaunchedHotelHotelList, // 酒店
  api_GET_EventsManagementLaunchedRoom, // 房间
  api_GET_EventsManagementLogisticReservationTimeCompetitionReservationTime, // 预定时间
  api_GET_EventsManagementHotelEntryHotelEntryLogisticEntryId, // 获取预定中的房间报名数据
  api_DELETE_EventsManagementHotelEntryHotelEntryHotelEntryId // 删除
} from '@/extend/api/gameswaggerApi/app';
import {
  Api_GET_EventsManagementLaunchedHotelHotelListQO,
  Api_GET_EventsManagementLaunchedRoomQO
} from '@/lib/form/game/swaggerForm';
export default {
  name: 'HotelList',
  components: {
    HotelOrder
  },
  props: {
    form: {
      type: Object,
      default() {
        return {};
      }
    },
    isShow: {
      type: Boolean,
      default: false
    },
    hasNext: {
      type: Boolean,
      default: true
    },
    toOrder: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false, // 酒店列表
      dataLoading: false, // 滚动加载
      tableLoading: false, // 已预订
      defaultHotelImg: defaultHotelImg,
      HotelListQO: new Api_GET_EventsManagementLaunchedHotelHotelListQO(),
      RoomQO: new Api_GET_EventsManagementLaunchedRoomQO(),
      hotelRatingCode: { // 酒店星级
        NoneStar: null,
        OneStar: 1,
        TwoStar: 2,
        ThreeStar: 3,
        FourStar: 4,
        FiveStar: 5
      },
      isTrain: false, // 是否是培训
      hotelData: [], // 酒店列表
      totalPage: 0, // 总条目数
      realWidth: '', // 酒店列表div真实高度
      screenHeight: '', // 酒店列表div高度
      hotelOrderTime: {}, // 后勤设置的酒店预定时间
      canOrder: true, // 是否可以预定，当前时间超过设置的酒店预定时间的结束时间，预定按钮不可用
      orderData: [] // 已订购的酒店
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict
    }),
    // 没有更多了
    noMore () {
      const Page = Math.ceil(this.totalPage / 10);
      return this.HotelListQO.Page >= Page;
    },
    disabled () {
      return this.dataLoading || this.noMore;
    }
  },
  watch: {
    isShow: {
      immediate: true,
      handler(val) {
        if (val) {
          if (this.$route.name.indexOf('Train') > -1) {
            this.isTrain = true; // 是培训
          }
          this.getData();
          this.getTime();
          if (this.form.id) {
            this.getOrderData();
          }
        }
      }
    }
  },
  created() {
    if (this.$route.name.indexOf('Train') > -1) {
      this.isTrain = true; // 是培训
    }
    this.getDict();
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    // 下一步 or 去结算
    toNext() {
      this.$emit('toNext');
    },
    // 获取酒店数据
    getData(page) {
      var that = this;
      that.loading = true;
      that.hotelData = [];
      that.HotelListQO.Page = page || 1;
      that.HotelListQO.SkipCount = (that.HotelListQO.Page - 1) * that.HotelListQO.MaxResultCount;
      that.HotelListQO.ProviderKey = this.$route.query.id;
      that.HotelListQO.IncludeRoom = false;
      that.HotelListQO.IncludeHotelRating = true;
      api_GET_EventsManagementLaunchedHotelHotelList(that.HotelListQO).then(res => {
        that.loading = false;
        let hotelList = res.items || [];
        that.totalPage = res.totalCount;
        if (hotelList.length > 0) {
          hotelList = hotelList.map(item => {
            return { ...item, isShowDetail: false, roomLoading: false };
          });
        }
        that.hotelData = hotelList;
        if (hotelList.length > 0) {
          that.$nextTick(() => {
            if (that.totalPage < 6) {
              if (that.$refs.contentBox && that.$refs.contentBox.offsetHeight) {
                that.realHeight = that.$refs.contentBox.offsetHeight;
                that.scrollHeight = that.realHeight > 800 ? 800 + 'px' : that.realHeight + 'px';
                that.$refs.scrollH.style.height = that.scrollHeight;
              }
            } else {
              that.$refs.scrollH.style.height = '800px';
            }
          });
        }
      }, (error) => {
        that.loading = false;
        that.$message({ type: 'error', message: error.error.message || '获取酒店列表失败！' });
      });
    },
    // 滚动加载
    load () {
      var that = this;
      that.dataLoading = true;
      that.HotelListQO.Page = that.HotelListQO.Page + 1;
      that.HotelListQO.SkipCount = (that.HotelListQO.Page - 1) * that.HotelListQO.MaxResultCount;
      that.HotelListQO.ProviderKey = this.$route.query.id;
      that.HotelListQO.IncludeRoom = true;
      that.HotelListQO.IncludeHotelRating = true;
      api_GET_EventsManagementLaunchedHotelHotelList(that.HotelListQO).then(res => {
        let hotelList = res.items || [];
        that.totalPage = res.totalCount;
        if (hotelList.length > 0) {
          hotelList = hotelList.map(item => {
            return { ...item, isShowDetail: false, roomLoading: false };
          });
          hotelList.forEach(function (item) {
            that.hotelData.push(item);
          });
        }
        that.dataLoading = false;
      }, (error) => {
        that.dataLoading = false;
        that.$message({ type: 'error', message: error.error.message || '获取酒店列表失败！' });
      });
    },
    // 获取后勤设置的酒店预定时间
    getTime() {
      var that = this;
      const providerName = this.isTrain ? 'T' : 'C';
      const form = {
        reservationCode: 'Hotel',
        providerKey: this.$route.query.id,
        providerName: providerName
      };
      api_GET_EventsManagementLogisticReservationTimeCompetitionReservationTime(form).then(res => {
        that.hotelOrderTime = res || {};
        var nowDay = new Date();
        nowDay.setTime(nowDay.getTime() - 24 * 60 * 60 * 1000);
        var endDay = new Date(res.endDateTime);
        if (nowDay > endDay) {
          that.canOrder = false;
        }
      }, (error) => {
        that.$message({ type: 'error', message: error.error.message });
      });
    },
    // 重置搜索表单
    reset() {
      this.HotelListQO = new Api_GET_EventsManagementLaunchedHotelHotelListQO();
      this.getData();
    },
    // 查看详情
    showDetail(item) {
      var that = this;
      item.isShowDetail = !item.isShowDetail;
      if (item.isShowDetail) {
        item.roomLoading = true;
        const id = item.id;
        that.RoomQO = new Api_GET_EventsManagementLaunchedRoomQO();
        that.RoomQO.LaunchedHotelId = id;
        that.RoomQO.IncludeBedType = true;
        that.RoomQO.IncludeBreakfastType = true;
        that.RoomQO.IsLocked = true;
        that.RoomQO.HasExtraBed = null;
        that.RoomQO.HasWindow = null;
        that.RoomQO.IncludeLauchedRoomStocks = true;
        api_GET_EventsManagementLaunchedRoom(that.RoomQO).then(res => {
          that.hotelData.forEach((temp, index) => {
            if (temp.id === id) {
              that.hotelData[index].hotel.rooms = res || [];
              that.hotelData[index].roomLoading = false;
            }
          });
          that.$nextTick(() => {
            if (that.$refs.contentBox && that.$refs.contentBox.offsetHeight) {
              that.realHeight = that.$refs.contentBox.offsetHeight;
              that.scrollHeight = that.realHeight > 800 ? 800 + 'px' : that.realHeight + 'px';
              that.$refs.scrollH.style.height = that.scrollHeight;
            }
          });
        }, error => {
          that.$message({ type: 'error', message: error.error.message || '获取房间失败！' });
          item.roomLoading = false;
        });
      } else {
        that.$nextTick(() => {
          that.realHeight = that.$refs.contentBox.offsetHeight;
          that.scrollHeight = that.realHeight > 800 ? 800 + 'px' : that.realHeight + 'px';
          that.$refs.scrollH.style.height = that.scrollHeight;
        });
      }
    },
    // 预订房间
    order(room, code) {
      const id = this.form.id;
      this.$refs.hotelOrder.lauchedRoomStocks = room.lauchedRoomStocks;
      this.$refs.hotelOrder.open(room, code, id, this.hotelOrderTime);
    },
    // 获取已预订的酒店房间
    getOrderData() {
      var that = this;
      that.tableLoading = true;
      api_GET_EventsManagementHotelEntryHotelEntryLogisticEntryId(this.form.id).then(res => {
        that.orderData = res || {};
        that.tableLoading = false;
      }, (error) => {
        that.tableLoading = false;
        that.$message({ type: 'error', message: error.error.message });
      });
    },
    // 编辑
    edit(row, code) {
      this.$refs.hotelOrder.open(row, code, row.id, this.hotelOrderTime);
    },
    // 删除
    remove(row) {
      var that = this;
      that.$confirm(`您确定要删除该预订吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api_DELETE_EventsManagementHotelEntryHotelEntryHotelEntryId(row.id).then((res) => {
          if (res) {
            that.getOrderData();
            that.$message({ type: 'success', message: '删除成功！' });
          }
        }, error => {
          that.$message({ type: 'error', message: '删除失败！' + (error.error && error.error.message || '') });
        });
      }).catch(() => {});
    },
    // 获取静态文件
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    errorPhoto() {
      const img = event.srcElement;
      img.src = this.defaultHotelImg;
    }
  }
};
</script>
<style scoped>
.search_box {
  padding: 15px 28px;
}
.search_box span {
  font-size: 14px;
  margin-right: 12px;
  display: inline-block;
}
.search_box .el-select {
  width: 160px;
  display: inline-block;
}
.search_box .el-input {
  width: 192px;
  display: inline-block;
}
.title {
  max-width: 300px;
  font-size: 16px;
  font-weight: 600;
  line-height: 24px;
}
.address {
  max-width: 300px;
  font-size: 12px;
  line-height: 24px;
  color: #828282;
}
.time {
  font-size: 14px;
  line-height: 30px;
}
.el-rate /deep/ .el-rate__icon {
  font-size: 20px;
}
.addBed {
  font-size: 12px;
  color: #828282;
}
.pt_30 {
  padding-top: 16px;
  font-size: 14px;
  line-height: 50px;
}
.el-table,.el-table /deep/ .el-table__body-wrapper {
  min-height: auto;
}
</style>
